package org.firebug.spring.boot.websocket.controller.web;

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ServerEndpoint("/apollo-socket-server/{sid}")
public class WebSocketServer {
    private static final Map<String, WebSocketServer> sidWebSocketMap = new ConcurrentHashMap<>();
    private Session session;

    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String sid) {
        System.out.println("onOpen()");
        this.session = session;
        sidWebSocketMap.put(sid, this);
    }

    @OnClose
    public void onClose() {
        System.out.println("onClose()");
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("onMessage(): " + message);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("onError()");
    }

    public static void sendMessage(String sid, String message) throws IOException {
        if (sidWebSocketMap.containsKey(sid)) {
            WebSocketServer webSocketServer = sidWebSocketMap.get(sid);
            webSocketServer.session.getBasicRemote().sendText(message);
        }
    }
}
